//'use strict';
var trim=function(str) {
  return str.replace(/(^\s*)|(\s*$)/g,'');
};
var JTE = function() {
  var o = {};
  o.print_prefix = '=';
  o._G = {};
  o.fnPool = {};
  o.clear = function() {
    this._G = {};
    return this;
  }
  o.assign = function(key, val) {
    this._G[key] = val;
    return this;
  }
  o.execute = function(tpl, name) {
    if (name == undefined) name = 'default';
    var fn_str = null;
    if (this.fnPool[name] != undefined) fn_str = this.fnPool[name];
    else {
      var reg = /<%=?([^>]+)%>/g;
      var CD = "var C = [];\n";
      var append = function(line) {
        var T = line.replace(/'/g, "\\\'").replace(/[\n\t]{1,}/g, " ");
        CD += "C.push('" + T + "');\n";
      }
      var CUR = 0;
      var CHR = 0;
      var TMP = null;
      var LGC = null;
      var m;
      while ((m = reg.exec(tpl)) != null) {
        append(tpl.slice(CUR, m.index));
        CHR = tpl[m.index + 2];
        LGC = m[1].replace(/\{([a-z0-9_\[\]\.]+)\}/gi, "__G__.$1");
        if (CHR == this.print_prefix) CD += "C.push(" + LGC + ");\n";
        else CD += LGC + "\n";
        CUR = m.index + m[0].length;
      }
      append(tpl.substr(CUR, tpl.length - CUR));
      CD += "return C.join('');\n";
      fn_str = CD;
      this.fnPool[name] = CD;
    }
    var ret = (function(__G__) {
      var r = '';
      try {
        //console.log(fn_str);
        var r = eval('(function(){' + fn_str + '}())');

      } catch(err) {
        console.log(err);
      }
      return r;
    } (this._G));
    return ret;
  }
  o.getParam = function(_name) {
    var pattern = new RegExp("(\\?|#|&)" + _name + "=([^&#]*)");
    var m = window.location.href.match(pattern);
    return (!m ? "": m[2]);
  }
  o.getTimeString = function(o_time, c_time) {
    t = c_time - o_time;
    if (t < 0) {
      var d = new Date();
      d.setTime(o_time * 1000);
      return d.getFullYear() + '年' + (d.getMonth() + 1) + '月' + d.getDate() + '日';
    }
    if (t < 5) return '刚刚';
    if (t < 60) return t + '秒前';
    if (t < 3600) return Math.floor(t / 60) + '分钟前';
    if (t < 86400) return Math.floor(t / 3600) + '小时前';
    if (t < 2592000) return Math.floor(t / 86400) + '天前';
    var d = new Date();
    d.setTime(o_time * 1000);
    if (t < 31104000) {
      return (d.getMonth() + 1) + '月' + d.getDate() + '日';
    }
    return d.getFullYear() + '年' + (d.getMonth() + 1) + '月' + d.getDate() + '日';
  }
  return o;
} ();

(
  function(window) {
    var tipNum = 2;

    var clientWidth = $(window).width() > 640 ? 640 : $(window).width();
    var clientHeight = $(window).height();
    var gdata = null;
    var questionCount = 0;
    var pageCount = 1;
    var pageNum;
    var answerResult = {};
    var answerIscrollArr = [];
    var coverIscroll = null;
    var resultIscroll = null;
    var touchName = 'ontouchstart' in window ? 'tap': 'click';
    var processVal = 0;
    var processTimeId = null;
    var isWechat = navigator.userAgent.indexOf('MicroMessenger') > -1;

    var queCount = 0;//当前题目
    var options = {
      bgImg: 'img/bg-default.jpg',
      logoImg: '/static/images/logo.default.png',
      //selAnswerBgcolor: 'rgb(215,215,215)',
      unselAnswerBgcolor:'#dbdbdb',
      selAnswerBgcolor: '#1da664',
      nextPageTime: 710,
      nextPageWaitingTime: 500,
      resultImgHeight: 170,
      answerImgWidth: 120,
      answerImgHeight: 80,
      coverDesc: {
        duration: 1000,
        animate: 'zoomIn'
      },
      coverTitle: {
        duration: 1000,
        animate: 'zoomIn' //shake
      },
      coverCoverImg: {
        duration: 0,
        animate: 'fadeInDownBig'
      },
      coverBtn: {
        duration: 1000,
        animate: 'lightSpeedIn'
      },
      mainTitle: {
        duration: 0,
        animate: ''
      },
      mainCoverImg: {
        duration: 0,
        animate: 'zoomInDown'
      },
      mainAnswers: {
        duration: 1000,
        animate: 'fadeInUp'
      },
      resultBox: {
        duration: 100,
        animate: 'slideInDown'
      }
    };
    function quizInit(data, containerSel, tplSel, opts) {
      try {
        //gdata = eval('(' + yoparentData + ')');
        gdata = window.yoparentData;
      } catch(err) {
        return false;
      }
      data = window.yoparentData;

      _initOptions(opts);
      var tree = _assignDataToTpl(tplSel);
      var contentBox = $(tree).find('[attr-content]');
      var pageBox = $(tree).find('[attr-page]');
      pageNum = pageBox.length;
      contentBox.css({
        width: clientWidth + 'px',
        height: clientHeight * pageBox.length + 'px'
      });
      pageBox.css({
        width: clientWidth + 'px',
        height: clientHeight + 'px'
      });
      $(tree).find('div.img-cover[img-src]').each(function() {
        var that = $(this);
        var curImgWidth = that.attr('img-width'),
          curImgHeight = that.attr('img-height');
        var tempHeight = (curImgHeight / curImgWidth) * clientWidth;
        tempHeight = tempHeight > clientHeight / 2 ? clientHeight / 2 : tempHeight;
        options.resultImgHeight = tempHeight;
        that.css({
          height: tempHeight + 'px'
        });
        that.find('img').css({
          width: '100%',
          height: tempHeight + 'px'
        });
        that.siblings('[answers-wrapper]').css({
          height: (clientHeight - tempHeight) - 155 + 'px'
        });
        that.siblings('[main-answers]').css({
          height: (clientHeight - tempHeight) + 'px'
        });

        //add by tian 按比例设置title的top值;
        that.siblings('[cover-title]').css({
          top: tempHeight*50/100
        });
      });
      $(tree).find('div.img-wrap[img-src]').each(function() {
        var that = $(this);
        try {
          var layout = JSON.parse(that.attr('data-layout'));
          var imgWrapWidth = (
              parseInt(clientWidth) -
              ((parseInt(layout.cols) + 1) * 8) -
              (parseInt(layout.cols) * 12)
            ) / parseInt(layout.cols);
          options.answerImgWidth = imgWrapWidth;
        } catch(e) {}
        var curImgWidth = that.attr('img-width'),
          curImgHeight = that.attr('img-height'),
          tempHeight = (curImgHeight / curImgWidth) * options.answerImgWidth;
        if (clientWidth > 500) {
          options.answerImgHeight = 150;
        }
        tempHeight = tempHeight > options.answerImgHeight ? options.answerImgHeight: tempHeight;
        that.css({
          width: options.answerImgWidth + 'px',
          height: tempHeight + 'px'
        });
        if (that.parent('li.hr[answer-item]').find('.pl').length !== 0) {
          that.parent('li.hr[answer-item]').css({
            'padding-left': options.answerImgWidth + 5 + 10 + 'px',
            'min-height': tempHeight + 16 + 'px'
          });
        } else {
          that.parent('li.hr[answer-item]').css({
            'padding-right': options.answerImgWidth + 5 + 10 + 'px',
            'min-height': tempHeight + 16 + 'px'
          });
        }
      });
      $(containerSel).append($(tree).children().get(0));
      var containerElment = $(containerSel);
      var pageElment = containerElment.find('[attr-page]');
      _initIscroll(containerElment);
      _initBgCoverImg(containerElment);
      _loadImg($(pageElment[pageCount]).find('div[img-src]'),
        function(obj) {
          var temp = $(obj).attr('style') + 'background:url(' + $(obj).attr('img-src') + ') top center no-repeat;background-size: 100% auto;background-origin:content-box;';
          $(obj).attr('style', temp);
        });
      _event(containerElment, pageElment);
      if (isWechat) {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = '/util/wechat/shr?v=' + Math.random();
        document.body.appendChild(script);
      }
    }
    function _event(containerElment, pageElment) {
      var content = containerElment.find('[attr-content]');

      $('.start').bind(touchName,
        function() {
          pageCount++;
          _nextPage(content, _getSliderHeight(clientHeight), pageElment);
          _loadImg($(pageElment[pageCount]).find('div[img-src]'),
            function(obj) {
              var temp = $(obj).attr('style') + 'background:url(' + $(obj).attr('img-src') + ') top center no-repeat;background-size: 100% auto;background-origin:content-box;';
              $(obj).attr('style', temp);
            });
        });

      //添加输入框的监听

      function checkAnswerCorrect(userInsert){
        var curQid = getCurrentQuestionId();
        var rightAnswerArr = yoparentData.questions[curQid].answer;
        var index = _.find(rightAnswerArr,function(oneAnswer){return oneAnswer === userInsert});
        // console.log(index);
        if(!!index){
          return true;
        }
        return false;
      }

      function highlightRight($that){
        $that.parent().parent().find('.right_wrapper').removeClass('right_unselect').addClass('right_select');
      }
      function unhighlightRight($that){
        $that.parent().parent().find('.right_wrapper').removeClass('right_select').addClass('right_unselect');
      }

      function gotoNextPage(){
        pageCount++;
        setTimeout(function() {
            _nextPage(content, _getSliderHeight(clientHeight), pageElment);
          },
          options.nextPageWaitingTime);
        _loadImg($(pageElment[pageCount]).find('div[img-src]'),
          function(obj) {
            var temp = $(obj).attr('style') + 'background:url(' + $(obj).attr('img-src') + ') top center no-repeat;background-size: 100% auto;background-origin:content-box;';
            $(obj).attr('style', temp);
          });

        if (pageCount >= pageNum) {
          quizResult(containerElment);
        }
      }
      function gotoPrevioustPage(){
        pageCount--;
        setTimeout(function() {
            _nextPage(content, _getSliderHeight(clientHeight), pageElment);
          },
          options.nextPageWaitingTime);
      }

      $('.insertbox').on('input',function(){
        var $that = $(this);
        var insertValue = $that.val();
        if(insertValue.length === 0){
          unhighlightRight($that);
          return;
        }

        if(checkAnswerCorrect($that.val())){
          highlightRight($that);
        }else{
          unhighlightRight($that);
        }
      });
      var hasResultPage = {};
      window.hasResultPage = hasResultPage;
      $('.right_wrapper').bind(touchName,function() {
        //如果处于正确的状态就进入下一页
        var $that = $(this);
        if($that.hasClass('right_select')){

          //将输入框置为只读状态，readOnly="true"
          var $parent = $that.parent().parent().parent();
          var $insertbox = $($parent.find('.insertbox'));
          $insertbox.attr('readOnly','true');

          //保存当前试题的选择结果
          if(!hasResultPage[getCurrentQuestionId()]){

            var uselect = {
              qid : getCurrentQuestionId() + 1,
              isTip:!!pageTip[getCurrentQuestionId()],
              uInput: $insertbox.val()
            };
            // console.log(uselect);

            hasResultPage[getCurrentQuestionId()] = uselect;
          }


          gotoNextPage();
        }
      });
      $('.left_wrapper').bind(touchName,function() {
        //如果处于正确的状态就进入上一页
        var $that = $(this);
        if($that.hasClass('left_select')){
          gotoPrevioustPage();
        }
      });

      var pageTip = {};
      $('.tip_wrapper').bind(touchName,function(){
        //判断当前页面是否有过提示
        if(pageTip[getCurrentQuestionId()]){
          return
        }
        if(tipNum === 0){
          return;
        }
        //如果已经作答过的题目，就不允许使用提示
        if(hasResultPage[getCurrentQuestionId]){
          return;
        }

        pageTip[getCurrentQuestionId()] = true;
        $that = $(this);
        var $insertboxWrapper = $($that.parent().parent().parent().find('.inserbox-wrapper'));
        $insertboxWrapper.find('.insertbox').hide();
        $insertboxWrapper.find('.reference_answer').show();

        highlightRight($that.parent());


        //减少一次提示的机会
        tipNum --;
        $('.tip_num').text(tipNum);

        //记录提示的内容
        var $that = $(this);
        //将输入框置为只读状态，readOnly="true"
        var $parent = $that.parent().parent().parent();
        var $insertbox = $($parent.find('.insertbox'));

        //保存当前试题的选择结果
        if(!hasResultPage[getCurrentQuestionId()]){

          var uselect = {
            qid : getCurrentQuestionId() + 1,
            isTip:!!pageTip[getCurrentQuestionId()],
            uInput: $insertbox.val()
          };
        //   console.log(uselect);

          hasResultPage[getCurrentQuestionId()] = uselect;
        }

      });



      //added by tian
      $('.continue').bind(touchName,
        function() {
          if(checkCouldInsertSelect()){
            return;
          }


          $that = $(this);
          if ($that.attr('disable') && $that.attr('disable') !== "0") {
            return;
          }
          $that.attr('disable',"1");




          //通知数据变化
          //console.log($that.attr('data-results'));
          roundDataUtil.selectItemBatch(pageCount-1, answerResult[pageCount-2]);

          //已经填满,这时进行翻页操作
          $that.parent().find('[answer-item]').attr('disable', 1);
          //answerAction($that);
          pageCount++;
          setTimeout(function() {
              _nextPage(content, _getSliderHeight(clientHeight), pageElment);
            },
            options.nextPageWaitingTime);
          _loadImg($(pageElment[pageCount]).find('div[img-src]'),
            function(obj) {
              var temp = $(obj).attr('style') + 'background:url(' + $(obj).attr('img-src') + ') top center no-repeat;background-size: 100% auto;background-origin:content-box;';
              $(obj).attr('style', temp);
            });

          if (pageCount >= pageNum) {
            quizResult(containerElment);
          }

          //pageCount++;
          //_nextPage(content, _getSliderHeight(clientHeight), pageElment);
          //_loadImg($(pageElment[pageCount]).find('div[img-src]'),
          //  function(obj) {
          //    var temp = $(obj).attr('style') + 'background:url(' + $(obj).attr('img-src') + ') top center no-repeat;background-size: 100% auto;background-origin:content-box;';
          //    $(obj).attr('style', temp);
          //  });
          //
          //if (pageCount >= pageNum) {
          //  quizResult(containerElment);
          //}
        });

      content.bind('touchstart',
        function() {});
      content.bind('touchmove',
        function(event) {
          event.preventDefault();
        });
      content.bind('touchend',
        function() {});
      content.find('[answer-item]').bind(touchName,
        function() {
          var $that = $(this);

          //如果选择的是已经选择过的,则进行撤消操作
          if ($that.attr('disable') !== "0") {
            $that.attr('disable', '0');
            //从该题目已选数据列表中清理
            clearCurrentSelect($that);
            //判断下一题按钮的高亮
            checkCouldNextPage($that);
            //清理已高亮的选项
            unhighlightSelect($that);

            return;
          }

          if(!checkCouldInsertSelect()){
            return;
          }

          $that.attr('disable', 1);//屏蔽掉现在的选项

          //高亮当前选项
          highlightSelect($that);

          //插入当前的选项
          var curQuestionAnswerSize = insertCurrentSelect($that);
          //判断下一题按钮的高亮
          checkCouldNextPage($that);

        });
      // $('#restart').bind(touchName,

      //     function() {
      //         location.href = 'http://weixin.qq.com/r/OUzUzH-EzCKzrTuv9xkr';
      //     });
      $('#share').bind(touchName,
          function() {
               $(".ending").removeClass("hide").addClass("show").addClass("animated").addClass("fadeIn");
               eventLogger && eventLogger.log("share_btn", "click", "share_btn");
               setTimeout(function() {
                       $(".ending").removeClass("show").removeClass("fadeIn").addClass("fadeOut");
                       setTimeout(function() {
                               $(".ending").addClass("hide").removeClass("fadeOut");
                           },
                           1000);
                   },
                   1500);
           });

      var isGameOver = false;
      $('.gameover').bind(touchName, function(){

        if(isGameOver){
          return;
        }
        isGameOver = true;

       //调转到最后一页
        pageCount = pageNum;
        setTimeout(function() {
            _nextPage(content, _getSliderHeight(clientHeight), pageElment);
          },
          options.nextPageWaitingTime);
        _loadImg($(pageElment[pageCount]).find('div[img-src]'),
          function(obj) {
            var temp = $(obj).attr('style') + 'background:url(' + $(obj).attr('img-src') + ') top center no-repeat;background-size: 100% auto;background-origin:content-box;';
            $(obj).attr('style', temp);
          });


        quizResult();
      });
      $(window).bind('load',
        function() {
          _orientationChange();
          window.onorientationchange = _orientationChange;
        });
    }
    function quizResult() {

      var psTime = (new Date()).getTime();
      $.post(window.resultUrl, {
          token: window.yoparentToken,
          createTime: window.yoparentStartTime,
          result: JSON.stringify(hasResultPage),
          quizId: window.yoparentData.id
        },
        function(ret) {
          if (ret === null) {
            window.alert('服务器错误，请稍后重试！');
            return;
          }
          if (ret.status === false) {
            window.location.reload();
            return;
          }
          var curTime = (new Date()).getTime();
          var deltaTime = curTime - psTime;
          deltaTime = deltaTime < 1500 ? 1500 : deltaTime;
          deltaTime = deltaTime > 2000 ? 0 : deltaTime;

          eventLogger && eventLogger.log("result", "load", "result");

          setTimeout(function() {
              showResult(ret);
            },
            deltaTime);
        });
    }

    function showResult(ret) {
      var resultData = JSON.parse(ret);

      var resultBox = $('.result-box');
      setTimeout(function() {
          var rimgWidth = (750 / 500) * options.resultImgHeight;
          if (rimgWidth > clientWidth) {
            rimgWidth = clientWidth;
          }
          //var resultTitle = JTE.clear().assign('result', ret.data).assign('quiz', gdata).execute(gdata.share.title, 'quiz_result');

          //计算分享的文字
          var descTemplate = _.template(trim($('#share-description-tpl').html()));
          var tempDesc = descTemplate({data:{
            total:_.keys(window.hasResultPage).length,
            tip: 2-tipNum,
            rate: resultData.data.rate
          }});
        //   console.log(tempDesc);
          if (!! window.wxReady) {
            window.yoparentWxConfig.desc = tempDesc;
            //window.yoparentWxConfig.imgUrl = "http://web58614.vhost058.cn/yoparent/images/50.png";
            window.wx.onMenuShareTimeline(window.yoparentWxConfig);
            window.wx.onMenuShareAppMessage(window.yoparentWxConfig);
          }
          //$('title').text(resultTitle);
          //$('.result-box .title').text(ret.data.title);
          //$('.result-box .title').text(ret.data.title);
          setTimeout(function(){
            new IScroll(document.querySelector('#result-wrapper'), {
              mouseWheel: true,
              tap: false,
              scrollbars: true,
              fadeScrollbars: true,
              interactiveScrollbars: false
            });

          },500);

          //$('.result-box').find('.result-img').css({
          //  width: rimgWidth + 'px',
          //  height: options.resultImgHeight + 'px',
          //}).css('border-radius', rimgWidth / 2 + 'px / ' + options.resultImgHeight / 2 + 'px');

          //$('.result-box').find('.result-img img').attr('src', ret.data.titleBg);
          //var resultDesc = JTE.clear().assign('result', ret.data).assign('quiz', gdata).execute(gdata.share.description, 'quiz_result_desc');
          var resultDescTemplate = _.template($('#result-tpl').html());
          $($('#result-wrapper li')[1]).html(resultDescTemplate({data:{
            total:_.keys(window.hasResultPage).length,
            tip: 2-tipNum,
            rate: resultData.data.rate
          }
          }));
          //$($('#result-wrapper li')[1]).text('你成功解读了' + ret.data.title + '双眼睛，击败了' + ret.data.description +'%的人。情绪的识别是情商的一个重要组成部分，在人际交往中有很大的帮助，分享给你的朋友，看看他们能识别多少吧！');
          resultBox.removeClass('hide').addClass('show').addClass('animated').addClass(options.resultBox.animate);
          $('.result-wrapper').css({
            //height: clientHeight - (50 + 113 + 40 + 15 + 15 + options.resultImgHeight) + 'px'
            height: clientHeight - 142 + 'px'
          });
          //new IScroll(document.querySelector('#result-wrapper'), {
          //  mouseWheel: true,
          //  tap: false,
          //  scrollbars: true,
          //  fadeScrollbars: true,
          //  interactiveScrollbars: false
          //});
        },
        options.resultBox.duration);

    }

    function getCurrentQuestionId(){
      return pageCount - 3;
    }
    function highlightSelect(obj){
      var colorV = options.selAnswerBgcolor;
      obj.css({
        'background-color': colorV
      });
    }
    function unhighlightSelect(obj){
      //var colorV = options.unselAnswerBgcolor;
      obj.css({
        'background-color': null
      });
    }
    function checkCouldInsertSelect(){
      var tempAnswerArr = answerResult[pageCount-2]
      if(!!tempAnswerArr && tempAnswerArr.length === 2){
        return false;
      }
      return true;
    }
    function insertCurrentSelect(obj) {
      var dataResults = obj.attr('data-results');
      if (!dataResults) {
        return;
      }

      var tempAnswerArr = answerResult[pageCount - 2];
      if (!tempAnswerArr) {
        tempAnswerArr = [];
      }

      tempAnswerArr.push(dataResults);
      answerResult[pageCount - 2] = tempAnswerArr;

      return tempAnswerArr.length;
    }
    function clearCurrentSelect(obj) {
      var dataResults = obj.attr('data-results');
      if (!dataResults) {
        return;
      }

      var tempAnswerArr = answerResult[pageCount - 2];
      var index = _.indexOf(tempAnswerArr, dataResults);
      tempAnswerArr.splice(index, 1);

      return tempAnswerArr.length;
    }
    function checkCouldNextPage(obj){
      var curPageSelectLen = 0;

      if(obj){
        var curPageSelect = answerResult[pageCount - 2];
        curPageSelectLen = !curPageSelect?0:curPageSelect.length;

      }

      var $btn = $(obj.parent().parent().parent().find('.continue'));
      if(curPageSelectLen == 2){
        $btn.css({
          'color': '#b2ed38'
        });
      }else{
        $btn.css({
          'color': '#acb0b9'
        });
      }
    }

    function answerAction(obj) {
      queCount++;
    }
    function _getSliderHeight(clientHeight) {
      return - (clientHeight + clientHeight * (pageCount - 2));
    }
    function _nextPage(content, dist, pageElment) {
      if (!content) {
        return;
      }

      var curPage = $(pageElment[pageCount - 1]);

      eventLogger && eventLogger.log("next", "load", curPage.attr("data-id"));

      content.addClass('transition');
      content.css('-webkit-transform', 'translate(0,' + dist + 'px)');
      content.css('transform', 'translate(0,' + dist + 'px)');
      if (pageCount >= pageNum){
        return;
      }
      setTimeout(function() {
          content.removeClass('transition');


          setTimeout(function() {
              curPage.find('[main-img]').removeClass('hide').addClass('show').addClass('animated').addClass(options.mainCoverImg.animate);
            },
            options.mainCoverImg.duration);
          setTimeout(function() {
              curPage.find('[main-title]').removeClass('hide').addClass('show').addClass('animated').addClass(options.mainTitle.animate);
            },
            options.mainTitle.duration);
          setTimeout(function() {
              curPage.find('[answers-wrapper]').removeClass('hide').addClass('show').addClass('animated').addClass(options.mainAnswers.animate);
              //var li = curPage.find('[main-answers] > li');
              //li.each(function() {
              //  $(this).find('[answer-item]').height($(this).height());
              //});
              //answerIscrollArr[pageCount - 2].refresh();
            },
            options.mainAnswers.duration);

          setTimeout(function() {
            curPage.find('[page-info]').removeClass('hide').addClass('show').addClass('animated').addClass(options.mainAnswers.animate);

          },options.mainAnswers.duration);

        },
        options.nextPageTime);
    }
    function _initIscroll(containerElment) {
      containerElment.find('#cover-scroller').css({
        height: clientHeight - (49 + 50 + containerElment.find('[cover-img]').height() + 15) + 'px'
      });
      //containerElment.find('[cover-wrapper]').css({
      //  height: clientHeight - (49 + 50 + containerElment.find('[cover-img]').height() + 15) + 'px'
      //});
      //coverIscroll = new IScroll(document.querySelector('[cover-wrapper]'), {
      //  mouseWheel: true,
      //  tap: false,
      //  scrollbars: true,
      //  fadeScrollbars: true,
      //  interactiveScrollbars: false
      //});
      var answersWrapper = containerElment.find('[answers-wrapper]');
      for (var i = 0; i < answersWrapper.length; i++) {
        var temp = new IScroll(answersWrapper[i], {
          mouseWheel: true,
          tap: false,
          scrollbars: true,
          fadeScrollbars: true,
          interactiveScrollbars: false
        });
        answerIscrollArr.push(temp);
      }

      //added by tian
      $('.question_explain_content_wrapper').css({
        //height: clientHeight - (50 + 113 + 40 + 15 + 15 + options.resultImgHeight) + 'px'
        height: clientHeight - ( 70 +  20 + options.resultImgHeight) + 'px'
      });
      //var explainDescWrapper = $('[explain-desc-wrapper]');
      //for (var i = 0; i < explainDescWrapper.length; i++) {
      //  var temp = new IScroll(explainDescWrapper[i], {
      //    mouseWheel: true,
      //    tap: false,
      //    scrollbars: true,
      //    fadeScrollbars: true,
      //    interactiveScrollbars: false
      //  });
      //}
    }
    function _coverAnimate(containerElment) {
      var cover = containerElment.find('[attr-cover]');
      var h1 = cover.find('[cover-title]'),
        img = cover.find('[cover-img] > img'),
        desc = cover.find('[cover-desc]'),
        start = $('[cover-btn]');
      setTimeout(function() {
          img.removeClass('hide').addClass('show').addClass('animated').addClass(options.coverCoverImg.animate);
        },
        options.coverCoverImg.duration);
      setTimeout(function() {
          h1.removeClass('hide').addClass('show').addClass('animated').addClass(options.coverTitle.animate);
        },
        options.coverTitle.duration);
      setTimeout(function() {
          desc.removeClass('hide').addClass('show').addClass('animated').addClass(options.coverDesc.animate);
        },
        options.coverDesc.duration);
      setTimeout(function() {
          start.removeClass('hide').addClass('show').addClass('animated').addClass(options.coverBtn.animate);
        },
        options.coverBtn.duration);
      setTimeout(function() {
          //coverIscroll.refresh();


          //coverIscroll = new IScroll(document.querySelector('[cover-wrapper]'), {
          coverIscroll = new IScroll($('#cover-scroller')[0], {
            mouseWheel: true,
            tap: false,
            scrollbars: true,
            fadeScrollbars: true,
            interactiveScrollbars: false
          });
        },
        1000);
    }
    function _initBgCoverImg(containerElment) {
      _loadCoverImg(containerElment.find('[cover-img]'),
        function(imgSrc, obj) {
          var imgObj = $(obj).find('img');
          imgObj.css({
            width: 100 + '%',
            height: 'atuo'
          });
          imgObj.attr('src', imgSrc);
        });


      _coverAnimate(containerElment);
    }
    function _loadBgImg(bgSrc, callback) {
      var img = new Image();
      img.src = bgSrc;
      img.onload = function() {



        callback(img.src);
      };
    }
    function _loadLogoImg(logoSrc, callback) {
      var img = new Image();
      img.src = logoSrc;
      img.onload = function() {
        callback(img.src);
      };
    }
    function _loadingImg(obj, callback) {
      var img = new Image();
      img.src = $(obj).attr('img-src');
      img.onload = function() {
        callback(obj);
      };
    }
    function _loadImg(imgsObj, callback) {
      if (typeof imgsObj === 'undefined' || imgsObj === null) {
        return;
      }
      for (var i = 0; i < imgsObj.length; i++) {
        _loadingImg(imgsObj[i], callback);
      }
    }
    function _loadCoverImg(obj, callback) {
      var img = new Image();
      img.src = $(obj).attr('img-src');
      img.onload = function() {
       callback(img.src, obj);
      };
    }
    function _initOptions(opts) {
      for (var val in opts) {
        if (typeof opts[val] === 'object') {
          for (var obj in opts[val]) {
            options[val][obj] = opts[val][obj];
          }
        } else {
          options[val] = opts[val];
        }
      }
    }
    function _assignDataToTpl(tplSel) {
      var posterTpl = $(tplSel).html();
      var compiled = _.template(posterTpl);
      var HTML = compiled(
        {
          'title' : gdata.title,
          'img_src': gdata.imgSrc,
          'description': gdata.description,
          'imgWidth': gdata.imgWidth,
          'imgHeight': gdata.imgHeight,
          'questions': gdata.questions
        }

      );
      var tree = document.createElement('div');
      tree.innerHTML = HTML;
      return tree;
    }
    var orientationFlags = false;
    function _orientationChange() {
      switch (window.orientation) {
        case 0:
          if (orientationFlags) {
            location.reload();
            orientationFlags = false;
          }
          break;
        case - 90 : if (!orientationFlags) {
          $('.orientation').removeClass('hide').add('show');
          orientationFlags = true;
        }
          break;
        case 90:
          if (!orientationFlags) {
            $('.orientation').removeClass('hide').add('show');
            orientationFlags = true;
          }
          break;
        case 180:
          if (orientationFlags) {
            location.reload();
            orientationFlags = false;
          }
          break;
      }
    }
    window.WeittQuiz = {
      run: quizInit
    };
  })(window);
